
# 根据SDCC实际地址进行修改
# SDCC_PREFIX=C:/Users/Administrator/.platformio/packages/toolchain-sdcc
SDCC_PREFIX=C:/Users/$(shell whoami)/.platformio/packages/toolchain-sdcc

CC      = $(SDCC_PREFIX)/bin/sdcc
PACKIHX = $(SDCC_PREFIX)/bin/packihx
AS      = $(SDCC_PREFIX)/bin/sdas8051
OBJCOPY = objcopy

ROMSIZE  ?= 4096
XRAMSIZE ?= 0
IRAMSIZE ?= 128
# -------------------------------------------------------------------------------------
# 小内存 code-代码 iram-内部RAM xram-外部RAM ， 需要根据自己的单片机进行修改
MCU_MODEL = -mmcs51
# MODEL  --model-small：  --model-medium 
MODEL     = --model-small
CODE_SIZE = --code-size $(ROMSIZE)
IRAM_SIZE = --iram-size 256
XRAM_SIZE = --xram-size $(XRAMSIZE)
# 设置xdata起始地址为0x0100 ,MCL51 合并了RAM访问， 外部RAM地址访问起始地址为 0x100,请不要修改这个值
XRAM_LOC  = --xram-loc 0x0100     

# -------------------------------------------------------------------------------------
# 公用头文件路径
C_INCLUDES += -I ..

# -------------------------------------------------------------------------------------

TARGET ?= firmware

# -------------------------------------------------------------------------------------

# AllDIRS := $(shell ls -R | grep '^\./.*:$$' | awk '{gsub(":","");print}') .

# CSRCS = $(foreach n,$(AllDIRS) , $(wildcard $(n)/*.c)) 

# CSRCS = $(wildcard lib/*.c)
# CSRCS += $(wildcard src/*.c)

# FSCRS = $(filter-out %main.c ,$(CSRCS))
FSCRS = $(CSRCS)
REL := $(FSCRS:%.c=%.rel)

# C_INCLUDES = -Iinclude  
# C_INCLUDES += -Isrc 
# C_INCLUDES += -Ilib 

# 合并 C 目标文件和汇编目标文件
ALLREL := $(REL) 

OUTDIR ?= ../../build

DEPS := $(FSCRS:%.c=%.d)

CFLAGS = $(MCU_MODEL) $(C_DEFS) $(C_INCLUDES) $(MODEL) --out-fmt-ihx --peep-return 
LDFLAGS = $(LIBDIR) $(LIBS) $(MCU_MODEL) $(MODEL) $(CODE_SIZE) $(IRAM_SIZE) $(XRAM_SIZE) $(XRAM_LOC) --out-fmt-ihx 

default:$(TARGET)

run:
	@echo $(FSCRS)
	@echo "---------------------"
	@echo $(REL)

	

%.rel : %.c
	@mkdir -p $(OUTDIR)
	@$(CC) -o $(OUTDIR)/$(notdir $@) $(CFLAGS) -c $<


$(TARGET) : $(ALLREL)
	@$(CC) -o $(OUTDIR)/firmware.ihx  $(foreach n,$(REL) ,$(OUTDIR)/$(notdir $(n)))  $(LDFLAGS)
	@$(PACKIHX) $(OUTDIR)/firmware.ihx  > $(OUTDIR)/soft.hex 
	@$(OBJCOPY) -I ihex $(OUTDIR)/soft.hex -O binary $(OUTDIR)/firmware.bin
	@python3 ../makehex.py $(OUTDIR)/firmware.bin $(ROMSIZE) > $(OUTDIR)/firmware.hex
	@-cd $(OUTDIR) && grep -A6 "Other memory" $(TARGET).mem


# @$(CC) -o $(OUTDIR)/firmware.ihx  $(OUTDIR)/*.rel $(LDFLAGS) 
# @$(PACKIHX) $(OUTDIR)/firmware.ihx  > $(OUTDIR)/firmware.hex 
# @-cd $(OUTDIR) && grep -A6 "Other memory" $(TARGET).mem


.PHONY: clean
clean:
	@rm -rf .pio 